from lxml import etree
from util.selenium.webdriver.common.by import By

from spider_data.spiderBaseMethod import bm
from util.g import g


def parse_stand(driver=None):
    try:
        stand_loc = (By.LINK_TEXT, '企业参与国家标准或行业标准制定情况汇总表')

        bm.detail_switch_iframe(driver=driver)

        bm.click(driver=driver, ele_loc=stand_loc)

        bm.wait(driver=driver, ele_loc=g.title_loc)

        WriteStandForm = list()
        i = 1
        while True:
            if i == 1:
                bm.wait(driver=driver, ele_loc=g.next_btn_loc)

            text = driver.page_source

            stand_li = parse_and_save_data(text=text)
            WriteStandForm.extend(stand_li)
            next_btn = bm.get_ele(driver=driver, ele_loc=g.next_btn_loc)
            onclick = None
            try:
                onclick = next_btn.get_attribute("onclick")
            except Exception as err:
                g.logger.error("get next page button\' attribute error: {}".format(err))
            if onclick is None:
                # driver.switch_to.default_content()
                break
            else:
                bm.click(driver=driver, ele_loc=g.next_btn_loc)
                bm.wait(driver=driver, ele_loc=g.table_loc)
                i += 1
        return {"key": "WriteStandForm", "value": WriteStandForm}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


def parse_and_save_data(text=''):
    try:
        tree = etree.HTML(text)

        records = tree.xpath('//tbody[@class="tableBody"]/tr')
        a = list()
        for r_index, r in enumerate(records):
            stand_item = {'stand_num': '', 'stand_name': '', 'stand_level': '', 'stand_way': ''}
            # stand_num	varchar(250)	标准编号    # stand_name	text	标准名称    # stand_level	tinyint	标准级别
            #  stand_way	tinyint	参与方式    # abstract	longtext	摘要

            name = r.xpath('./td[1]/text()')
            stand_level_name = r.xpath('./td[2]/text()')
            num = r.xpath('./td[3]/text()')
            stand_way_name = r.xpath('./td[4]/text()')
            stand_item['stand_num'] = bm.join_and_repalce(num)
            stand_item['stand_name'] = bm.join_and_repalce(name)
            stand_item['stand_level'] = stand_level_name
            stand_item['stand_way'] = stand_way_name
            a.append(stand_item)
        return a
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


